package cn.coufran.springboot.starter.json;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Hibernate工具类
 * @author Coufran
 * @version 2.0.1
 * @since 2.0.1
 */
public class HibernateUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtils.class);

    private static Method isInitializedMethod;

    static {
        try {
            Class<?> hibernateClass = Class.forName("org.hibernate.Hibernate");
            HibernateUtils.isInitializedMethod = hibernateClass.getMethod("isInitialized", Object.class);
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            LOGGER.warn("could not find method org.hibernate.Hibernate.isInitialized(Object)");
            isInitializedMethod = null;
        }
    }

    public static boolean isInitialized(Object proxy) {
        if (isInitializedMethod != null) {
            try {
                return (boolean) isInitializedMethod.invoke(null, proxy);
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOGGER.warn("method org.hibernate.Hibernate.isInitialized(Object) error", e);
                return true;
            }
        }
        return true;
    }
}
